package main

import (
	"flag"
	"fmt"
	"net/http"

	"mall/common/errorx"
	"mall/service/backend/api/internal/config"
	"mall/service/backend/api/internal/handler"
	"mall/service/backend/api/internal/svc"
	newErrorx "mall/service/backend/common/errorx"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"
)

var configFile = flag.String("f", "etc/backend.dev.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf, rest.WithCors(c.CROSConf.Address))
	defer server.Stop()
	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	// 自定义错误
	httpx.SetErrorHandler(func(err error) (int, any) {
		if e, ok := err.(*errorx.CodeError); ok {
			return http.StatusOK, e.Data()
		}

		if e, ok := err.(*newErrorx.CodeError); ok {
			return http.StatusOK, e.Data()
		}

		if e, ok := err.(*newErrorx.ApiError); ok {
			return int(e.Code), e
		}

		if gstatus, ok := status.FromError(err); ok { // grpc err错误
			grpcCode := uint32(gstatus.Code())
			if msg := gstatus.Message(); msg != "" {
				e := errorx.NewCodeError(grpcCode, msg)
				return http.StatusOK, e.Data()
			}

			if msg := errorx.GetMsg(grpcCode, false); msg != "" { // 区分自定义错误跟系统底层、db等错误，底层、db错误不能返回给前端
				e := errorx.NewCodeError(grpcCode, msg)
				return http.StatusOK, e.Data()
			}
		}

		e := errorx.NewDefaultError(err.Error())
		return http.StatusOK, e.Data()
		// return http.StatusInternalServerError, nil
	})

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
